package user

import (
	"context"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"time"
	"yangming-college/app/usercenter/cmd/v1/api/internal/svc"
	"yangming-college/app/usercenter/cmd/v1/api/internal/types"
	"yangming-college/common/cryptx"
	"yangming-college/common/jwtx"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	//判断用户是否存在
	var account types.Account
	err = l.svcCtx.DB.Where("phone = ?", req.Phone).First(&account).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, errors.Wrapf(err, "用户不存在")
		}
		return nil, errors.Wrapf(err, "查找用户失败")
	}
	// 判断密码是否正确
	password := cryptx.PasswordEncrypt(l.svcCtx.Config.Salt, req.Password)
	if password != account.Password {
		return nil, errors.Wrapf(err, "密码不正确")
	}

	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.JwtAuth.AccessExpire

	accessToken, err := jwtx.GetToken(l.svcCtx.Config.JwtAuth.AccessSecret, now, accessExpire, account.AccountId)
	if err != nil {
		return nil, errors.Wrapf(err, "token生成失败")
	}

	return &types.LoginResp{
		AccessToken:  accessToken,
		AccessExpire: now + accessExpire,
		RefreshAfter: now + accessExpire/2,
	}, nil
}
